package com.heima.controller;
import com.heima.Result;
import com.heima.util.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("upload")
@Tag(name = "上传图片接口")
@Slf4j
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    @Operation(summary = "上传图片")
    public Result upload(MultipartFile file) {
        log.info("文件上传：{}",file);
        try {
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建日期文件夹结构 yyyy-MM-dd
            LocalDate today = LocalDate.now();
            String dateFolder = today.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

            //新的文件名 (日期文件夹/UUID.扩展名)
            String newFileName = dateFolder + "/" + UUID.randomUUID().toString() + extension;

            String filePath = null;
            filePath = aliOssUtil.upload(file.getBytes(), newFileName);
            log.info("文件上传成功：{}",filePath);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }
        return Result.error("文件上传失败");
    }
}
